package com.itheima.tliassystem.aspect;


import com.itheima.tliassystem.mapper.EmpLoginMapper;
import entity.Emp;
import entity.EmpLoginLog;
import entity.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
@Aspect
public class EmpLoginAspect {
    @Autowired
    EmpLoginMapper empLoginMapper;
    @Autowired
    HttpServletRequest request;

    @Around("@annotation(com.itheima.tliassystem.aspect.EmpLoginLog)")
    public Object login(ProceedingJoinPoint PJP)  {
        long begin = System.currentTimeMillis();
        Result result = null;
        String token = "";
        Short flag = 0;
        try {
            result = (Result) PJP.proceed();
            if (result != null) {
                token = (String) result.getData();
                flag = 1;
            }
        } finally {
            long end = System.currentTimeMillis();
            EmpLoginLog empLoginLog = new EmpLoginLog();
            //获取登录ID 需要获取请求头中的JWT令牌 在解析令牌
            Object[] args = PJP.getArgs();
            Emp emp = (Emp) args[0];
            Integer id = emp.getId();
            //获取登录用户名
            String username = emp.getUsername();
            //获取登录密码
            String password = emp.getPassword();
            //获取登录时间
            LocalDateTime now = LocalDateTime.now();
            //获取登录是否成功 1:成功 0:失败
            empLoginLog.setIsSuccess(flag);
            //成功后 下发的jwt令牌
            empLoginLog.setJwt(token);
            //登录耗时 单位:ms
            long costTime = end - begin;
            empLoginLog.setId(id);
            empLoginLog.setUsername(username);
            empLoginLog.setPassword(password);
            empLoginLog.setLoginTime(now);
            empLoginLog.setCostTime(costTime);
            empLoginMapper.insert(empLoginLog);

            //异步记录日志
            new Thread(new Runnable() {
                @Override
                public void run() {
                    empLoginMapper.insert(empLoginLog);
                }
            }).start();


            return result;
        }
    }
}
